//导入 espress
const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
//导入 jwt
const jwt = require("jsonwebtoken");

// const bodyParser = require("body-parser");
// //解析 JSON 格式的请求体的中间件
// const jsonParser = bodyParser.json();

const app = express();
app.use(cors());
const db = mysql.createPool({
  host: "localhost",
  port: "3306",
  user: "root",
  password: "123446",
  database: "react_management",
});

//创建路由对象
const router = express.Router();

router.get("/logins", (req, res) => {
  res.json({
    a: 1,
  });
});

//创建路由
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  console.log(username, password);
  db.query(
    `select * from user where uid = '${username}' and password = '${password}'`,
    (err, data) => {
      // console.log(err);
      // console.log(data);
      if (err) {
        res.json({
          code: "2001",
          message: "获取数据库时发生错误",
          data: null,
        });
        return;
      }
      if (!data.length) {
        return res.json({
          code: "2002",
          message: "用户名或密码错误",
          data: null,
        });
      } else {
        //创建（生成） token
        let token = jwt.sign(
          {
            username: "209000222",
          },
          "pengqingnan",
          {
            expiresIn: 60 * 60, //单位是秒
          }
        );
        return res.json({
          code: 200,
          msg: "操作成功",
          token,
        });
        // return res.send({
        //   status: 200,
        //   toekn: token,
        // });
      }
    }
  );
});

router.get("/api/search", (req, res) => {
  res.send("内容搜索");
});

//暴露 Router
module.exports = router;
